import { getAuthRole, updateAuthRole } from '@/api/system/user'
import { formatDate } from '@/utils/common'
import { message } from '@/utils/message'
import type { PaginationProps } from '@pureadmin/table'
import { useGlobal } from '@pureadmin/utils'
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export function useAuthRole() {
  const data = reactive({
    form: {
      nickName: undefined,
      userName: undefined,
      userId: undefined,
    },
  })
  const { form } = toRefs(data)
  const router = useRouter()
  const route = useRoute()
  const roleRef = ref(null)

  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const dataList = ref([])
  const loading = ref(true)
  const showSelection = true
  const { $config } = useGlobal<GlobalPropertiesApi>()
  const osTypes = [0, $config.OSType]
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  })
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: 55,
      align: 'left',
      hide: ({ checkList }) => !checkList.includes('勾选列'),
    },
    {
      label: '序号',
      type: 'index',
      width: 70,
      hide: ({ checkList }) => !checkList.includes('序号列'),
    },
    {
      label: '角色编号',
      prop: 'roleId',
      minWidth: 80,
    },
    {
      label: '角色名称',
      prop: 'roleName',
      minWidth: 120,
    },
    {
      label: '权限字符',
      prop: 'roleKey',
      minWidth: 120,
    },
    {
      label: '创建时间',
      minWidth: 180,
      prop: 'operTime',
      formatter: ({ operTime }) => formatDate(operTime),
    },
  ]

  /** 搜索按钮操作 */
  function onSearch() {
    const userId: any = route.params && route.params.userId
    if (userId) {
      loading.value = true
      getAuthRole(osTypes, userId).then((response: any) => {
        const start = (pagination.currentPage - 1) * pagination.pageSize
        const end = start + pagination.pageSize
        const data = response.data.roles.slice(start, end)
        form.value = response.data.user
        dataList.value = data
        pagination.total = response.data?.roles.length
        nextTick(() => {
          dataList.value.forEach((row) => {
            if (row.flag) {
              roleRef.value.getTableRef().toggleRowSelection(row)
            }
          })
        })
        loading.value = false
      })
    }
  }

  /** 单击选中行数据 */
  function clickRow(row) {
    roleRef.value.getTableRef().toggleRowSelection(row)
  }

  /** 保存选中的数据编号 */
  function getRowKey(row) {
    return row.roleId
  }

  /** 提交按钮 */
  function submitForm() {
    const userId = form.value.userId
    const rIds = ids.value.join(',')
    updateAuthRole({ userId: userId, roleIds: rIds }).then(() => {
      message('授权成功', { type: 'success' })
      cancel()
    })
  }

  /** 关闭按钮 */
  function cancel() {
    router.replace('/user')
  }

  /** 改变分页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  /** 改变当前分页 */
  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  /** 改变多选项 */
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.roleId)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  onMounted(() => {
    onSearch()
  })

  return {
    form,
    roleRef,
    loading,
    columns,
    dataList,
    pagination,
    showSelection,
    cancel,
    clickRow,
    getRowKey,
    submitForm,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
  }
}
